package com.shun.service

import com.shun.commons.ApiUtils
import com.shun.commons.exception.ApiException
import com.shun.commons.exception.AppException
import com.shun.entity.User
import com.shun.entity.UserInfo
import com.shun.feign.UserClient
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service

/**
 * Created by rainbow on 2017/8/9.
 *一事专注，便是动人；一生坚守，便是深邃！
 */
@Service
class AuthService {
    @Autowired
    private lateinit var utils: ApiUtils


    @Autowired
    private lateinit var client: UserClient

    @Autowired
    private lateinit var redisTemplate: StringRedisTemplate

    @Autowired
    private lateinit var mongoTemplate: MongoTemplate

    //用户登录
    fun login(params: Map<String, String>): User? {
        val userInfo = getUserFromSession(client.login(params)["session"].toString()) ?: throw ApiException("无效的session")

        return mongoTemplate.findOne(Query.query(Criteria("uuid").`is`(userInfo.uuid).and("status").`is`(1)), User::class.java) ?: throw ApiException("请联系管理员开通访问权限")
    }


    //获取登录用户信息
    fun info(mobile: String): User {
        val query = Query.query(Criteria("mobile").`is`(mobile))
        return mongoTemplate.findOne(query, User::class.java)
    }


    private fun getUserFromSession(session: String): UserInfo? {
        val keys = redisTemplate.keys(("cch:session:*:*:$session")).toTypedArray()
        if (keys.size != 1) return null
        val info = redisTemplate.opsForValue().get(keys[0]) ?: return null
        return utils.mapper.readValue(info, UserInfo::class.java)
    }

    private fun exists(mobile: String) = mongoTemplate.exists(Query.query(Criteria("mobile").`is`(mobile)), User::class.java)
}